package com.googlecode.garbagecan.dbtest;
import java.io.File;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class LsbGenerator {

	private List<String> list = new ArrayList<String>();

	// private String inputFile = "./../res/lsb.stream.sample";
	// private String inputFile =
	private String inputFile = "/scratch/qa/perf/zhjliu/performance_tool/lpt/loaders.performanceTest/res/lsb.stream.sample";

	private String outputFile = null;

	// private String outputPath = "./../out/";
	private String outputPath = "/scratch/qa/perf/zhjliu/as7/lsfep3/work/cluster_ep3/logdir/stream/aaa/";

	private int jobId = 0;

	private int length = 0;

	private Connection conn;
	private PreparedStatement ps;

	public LsbGenerator(String fileName, int length) {
		this.length = length;
		// this.outputFile = "/scratch/dev/fkong/test/" + fileName;

		// lsb.stream output
		// this.outputFile =
		// "/scratch/qa/cliu/lsf/lsfTop/work/clusterPF/logdir/stream/"
		this.outputFile = outputPath + fileName;

		File file = new File(outputFile);
		// if (file.exists()) {
		// file.delete();
		// }
		
		try {
			this.initDB();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			readTemplateFile();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void generate() throws Exception {
		List lll = new ArrayList();
		String s1 = " \"7.03\" ";
		String s2 = " 102 ";
		// String s3 = " 2 \"xianlinux1\" \"xianlinux2\" ";
		// String s3 = " \"JOB_FINISH\" ";
		String s3 = "JOB_FINISH";

		//		String hosts = this.generateHosts();
//		FileWriter fw = new FileWriter(outputFile, true);
//		BufferedWriter bw = new BufferedWriter(fw);
//		Random random = new Random(1);
		// 
		// int day = 1;
		// int days = 1;
		//System.out.println("start write!");
		// for (int day = 0; day < days; day++) {
		// for (int day = 0; day < days; day++) {
		for (int i = 0; i < length; i++) {
			//System.out.println(lll.size());
			// for one job
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			// int hour = 0;
			// while (true) {
			// int t = random.nextInt();
			// if (t > 0) {
			// hour = t % 3;
			// break;
			// }
			// }
			// cal.set(Calendar.HOUR_OF_DAY, 0);
			// cal.add(Calendar.HOUR_OF_DAY, hour);
			// cal.add(Calendar.DATE, day);

			++jobId;
			// System.out.println("i:"+i);
			for (String line : list) {
				cal.add(Calendar.SECOND, 1);
				long l = cal.getTimeInMillis();
				String time = "" + l;
				long ll = l + 400 * 1000;
				time = time.substring(0, time.length() - 3);
				String time1 = "" + ll;
				time1 = time1.substring(0, time1.length() - 3);

				int idx1 = line.indexOf(s1);
				int idx2 = line.indexOf(s2);
				int idx3 = line.indexOf(s3);

				// if (idx3 > 0) {
				// line = line.substring(0, idx3) + hosts
				// + line.substring(idx3 + s3.length());
				// }

				if (idx2 > 0) {
					line = line.substring(0, idx2) + " " + jobId + " "
							+ line.substring(idx2 + s2.length());
				}

				if (idx1 > 0) {
					if (idx3 > 0) {
						// line = line.substring(0,idx3) + " \"7.03\" " + time1
						// + line.substring(idx2);
						line = "\"JOB_FINISH\"" + " \"7.03\" " + time1
								+ line.substring(idx2);
					} else {
						line = line.substring(0, idx1) + " \"7.03\" " + time
								+ line.substring(idx2);
					}
				}

				
				line += "\n";
				lll.add(line);
				
//				 File file = new File(outputFile);
//				 if(file.length()>500*1024*1024)
//				 {
//				 File file0 = new File(file.getAbsolutePath()+".0");
//				 if(file0.exists())
//				 {
//				 file0.delete();
//				 }
//				 if(bw!=null) bw.close();
//				 if(fw!=null) fw.close();
//				 file.renameTo(new File(file.getAbsolutePath()+".0"));
//				 fw = new FileWriter(outputFile,true);
//				 bw = new BufferedWriter(fw);
//				 //bw.write(line);
//				 }
//				 bw.write(line);
			}
			//bw.flush();
		}
		// }
		// }

//		try {
//			bw.close();
//			fw.close();
//		} catch (Exception ex) {
//			// ignore
//		}
		//System.out.println("before insert:" + lll.size());
		insertDB(lll);
	}

	private void initDB() throws Exception {
		conn = getConnection();
		conn.setAutoCommit(false);
		String sql = "insert into fkong_lsbevent3(full_value)values(?)";
		ps = conn.prepareStatement(sql);
	}

	private void insertDB(List list) throws Exception {
		for (int i = 0; i < list.size(); i++) {
			ps.setObject(1, list.get(i));
			ps.addBatch();
		}
		ps.executeBatch();
		ps.clearBatch();
		conn.commit();
	}

	private Connection getConnection() throws SQLException,
			ClassNotFoundException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url = "jdbc:oracle:thin:@perfdb01:1521:orcl";
		Connection conn = DriverManager.getConnection(url, "fkong2", "fkong2");
		return conn;
	}

	private void coloseConnection(Connection conn) throws SQLException,
			ClassNotFoundException {
		conn.close();
	}

	private void readTemplateFile() throws Exception {
		RandomAccessFile raf = new RandomAccessFile(inputFile, "rw");
		while (true) {
			String line = raf.readLine();
			if (line == null)
				break;

			list.add(line);
		}
		//System.out.println(list);
		raf.close();
	}

	private String generateHosts() throws Exception {
		// readTemplateFile();
		StringBuffer sb = new StringBuffer();
		// host number
		sb.append(" 2 ");
		for (int i = 1; i <= 2; i++) {
			sb.append("\"xianlinux").append(i).append("\" ");
		}
		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		try {
			LsbGenerator dg = null;
			dg = new LsbGenerator("lsb.stream", 1000);
			while (true) {
				for( int i = 0; i < 100; i++) {
					dg.generate();
				}
				System.out.println(System.currentTimeMillis() + " : sleep 5 minutes.");
				Thread.sleep(5 * 60 * 1000);
				//Thread.sleep(5 * 1000);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}